package com.camel.docker.controller;

import com.alibaba.fastjson.JSONObject;
import com.camel.docker.config.WebSocketServer;
import com.camel.docker.entity.Result;
import com.camel.docker.entity.search.ContainerAddForm;
import com.camel.docker.entity.search.ContainerForm;
import com.camel.docker.enums.ResultEnum;
import com.camel.docker.enums.StartType;
import com.camel.docker.service.ContainerCreatorService;
import com.camel.docker.service.DockerClientService;
import com.camel.docker.utils.ResultUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.Container;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/container")
public class ContainersController extends BaseController {

    public static final String CONTAINER_CUNSTOM_KEY = "com.camel.docker.label";

    @Autowired
    public DockerClientService dockerClientService;

    @Autowired
    public WebSocketServer webSocketServer;

    @Autowired
    private ContainerCreatorService containerCreatorService;

    /**
     * 查询容器列表
     *
     * @param container
     * @return
     */
    @GetMapping
    public Result containers(ContainerForm container) {
        DockerClient dockerClient = dockerClientService.connect();
        PageInfo<Container> pageInfo = getPageInfo();
        List<Container> containerList = container.buildListCmd(dockerClient).exec();
        pageInfo.setList(containerList);
        return ResultUtil.success(pageInfo);
    }

    /**
     * 获取指定容器
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result container(@PathVariable String id) {
        if (StringUtils.isEmpty(id)) {
            return ResultUtil.error(ResultEnum.NOT_VALID_PARAM.getCode(), "无效的容器");
        }
        DockerClient dockerClient = dockerClientService.connect();
        try {
            InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(id).exec();
            return ResultUtil.success(JSONObject.toJSON(inspectContainerResponse));
        } catch (NotFoundException e) {
            return ResultUtil.error(ResultEnum.NOT_VALID_PARAM.getCode(), "找不到对应的容器");
        }
    }

    /**
     * 创建指定容器
     *
     * @param containerAddForm
     * @return
     */
    @PostMapping
    public Result save(@RequestBody ContainerAddForm containerAddForm) {
        if (ObjectUtils.isEmpty(containerAddForm.getStartInfo())) {
            return ResultUtil.error(500, "请选择容器启动方式");
        } else if (StartType.GIT.getCode().equals(containerAddForm.getStartInfo().getStartType())) {
            return newContainerByGit(containerAddForm);
        } else if (StartType.FILESYSTEM.getCode().equals(containerAddForm.getStartInfo().getStartType())) {
            return newCantainerByFileSystem(containerAddForm);
        }
        return ResultUtil.error(500, "容器创建失败，未找到合适的创建方式");
    }

    /**
     * 删除指定容器
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable String id) {
        DockerClient client = dockerClientService.connect();
        client.removeContainerCmd(id).withForce(true).exec();
        return ResultUtil.success("删除容器成功");
    }

    /**
     * 停止指定容器
     *
     * @param id
     * @return
     */
    @DeleteMapping("/stop/{id}")
    public Result stop(@PathVariable String id) {
        DockerClient client = dockerClientService.connect();
        client.stopContainerCmd(id).exec();
        return ResultUtil.success("停止容器成功");
    }

    /**
     * 文件系统创建容器
     *
     * @param containerAddForm
     * @return
     */
    public Result newCantainerByFileSystem(ContainerAddForm containerAddForm) {
        return containerCreatorService.creatFromFileSystem(containerAddForm);
    }

    /**
     * GIT 方式创建容器
     *
     * @param containerAddForm
     * @return
     */
    public Result newContainerByGit(ContainerAddForm containerAddForm) {
        return containerCreatorService.creatFromGit(containerAddForm);
}
}
